import pymongo
import json
from ReachMongo import FetchRules
import time
from data import getData

ISOTIMEFORMAT='%Y-%m-%d %X'
data = []
rules = []
todolist = []


def check():
    rulelist = FetchRules()
    rulechecked = []
    for rule in rulelist:
        rj = json.loads(rule)
        
        for this in rj['thislist']:
            for da in data:
               if int(da['pin']) == this['TaskID']:
                    thistype = {
                        2 : this['Threshold'] - da['data'],
                        1 : da['data'] - this['Threshold']
                        }
                    if thistype.get(this['ThisTpye']) > 0:
                        global todolist
                        tag = 0
                        for todo in todolist:
                            if todo['_id'] == rj['_id']:
                                tag = 1
                        if tag == 0:
                            todolist.append(rj)
                        
                        
                       
def dolist():
    global todolist
    for todo in todolist:
        log = 'Rule:'+ todo['name'] + '\t reached at ' + time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) ) + '\n'
        for that in todo['thatlist']:
            thatid = {
                0 : 'record',
                1 : 'message',
                }
            thattype = {
                0 : 'log',
                1 : 'message',
                2 : 'message & log'
                }
            thataction = {
                0 : todo['thatlist']
                }
            log += thatid.get(that['TaskID']) + '\t' + thattype.get(that['ActionTpye']) + '\t' + json.dumps(thataction.get(that['Action']))
    
    todolist = []
    return log




def databuffer():
    global data
    data = json.loads(getData())


def rulebuffer():
    global rules
    rules = FetchRules()




if __name__ == "__main__":
    
    rulebuffer()
    while True:
        databuffer()
        check()
        print dolist()
        time.sleep(20)


		
